import { app, shell, BrowserWindow, Tray, Menu, nativeImage, ipcMain } from 'electron'
import { join } from 'node:path'
import './system/logger';
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { getUserAgent, getAvailablePort, openTempPath, openAppPath } from './utils'
import setupIpcHandlers from './ipcHandlers';
import Server from './server/index';
import { Conf } from 'electron-conf/main'
import log from 'electron-log'; 

const conf = new Conf()

conf.set('proxyUrl', import.meta.env.VITE_SITE_URL)

// 如果要测试打包后的应用升级，需要解开下面注释掉的代码
// Object.defineProperty(app, 'isPackaged', {
//   get() {
//     return true;
//   }
// });

const RESOURCES_PATH = join(__dirname, `../../resources`);

const getAssetPath = (...paths) => {
  return join(RESOURCES_PATH, ...paths);
};

/**
 * Prevent electron from running multiple instances.
 */
const isSingleInstance = app.requestSingleInstanceLock();
if (!isSingleInstance) {
  app.quit();
  process.exit(0);
}

app.on('second-instance', restoreOrCreateWindow);

// /**
//  * Disable Hardware Acceleration to save more system resources.
//  */
// app.disableHardwareAcceleration();

let win = null

async function createWindow() {
  // Create the browser window.
  let mainWindow = new BrowserWindow({
    minWidth: 1450,
    width: 1450,
    height: 1000,
    minHeight: 1000,
    // titleBarStyle: 'hidden',
    // trafficLightPosition: { x: 10, y: 20 },
    // titleBarOverlay: true,
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true,
      nodeIntegration: false
    }
  })



  app.on('ready', (event) => {
    log.info('app ready :', event);
    try {
      console.info('启用硬件加速:', event);
      log.info('启用硬件加速',event );
      app.enableHardwareAcceleration();
      createWindow();
    } catch (error) {
      console.error('Hardware acceleration failed, falling back to software rendering:', error);
      log.error('Hardware acceleration failed, falling back to software rendering:', error);
      // 向用户显示错误提示
      dialog.showErrorBox('Hardware Acceleration Error', '请升级驱动程序或者关闭硬件加速。正在尝试关闭硬件加速。');
      // 禁用硬件加速
      app.disableHardwareAcceleration();
      app.commandLine.appendSwitch('disable-gpu');
      app.commandLine.appendSwitch('disable-software-rasterizer');
      createWindow();
    }
  });


  mainWindow.on('ready-to-show', () => {
    mainWindow?.show();

    if (is.dev) {
      mainWindow?.webContents.openDevTools();
    }
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    await mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    await mainWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'workShotstack/home' })
  }

  mainWindow.webContents.setUserAgent(getUserAgent(mainWindow))

  // 添加窗口关闭事件处理
  mainWindow.on('close', (event) => {
    if (!app.isQuitting) {
      event.preventDefault()
      mainWindow.hide()

      // macOS 隐藏 Dock 图标
      if (process.platform === 'darwin') {
        app.dock.hide()
      } else {
        mainWindow.setSkipTaskbar(true)
      }

      return false
    }
  })

  // 创建托盘图标
  const tray = new Tray(nativeImage.createFromPath(
    process.platform === 'darwin' ? getAssetPath('tray.png') : getAssetPath('tray.ico')
  ))
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主界面',
      click: () => {
        if (process.platform === 'darwin') {
          app.dock.show()
        } else {
          mainWindow.setSkipTaskbar(false)
        }
        mainWindow.show()
      }
    },
    {
      type: 'separator'
    },
    {
      label: '文件',
      submenu: [
        {
          label: '打开临时目录',
          click: () => openTempPath()
        },
        {
          label: '打开数据存储目录',
          click: () => openAppPath()
        }
      ]
    },
    {
      type: 'separator'
    },
    {
      label: '退出',
      click: () => {
        app.isQuitting = true
        app.quit()
      }
    }
  ])

  tray.setToolTip(import.meta.env.VITE_APP_SHORT_NAME)
  tray.setContextMenu(contextMenu)

  // 点击托盘图标显示窗口
  tray.on('click', () => {
    mainWindow.show()
  })

  return mainWindow
}

export async function restoreOrCreateWindow() {
  win = BrowserWindow.getAllWindows().find(w => !w.isDestroyed());

  if (win === undefined) {
    win = await createWindow();
  }

  if (win.isMinimized()) {
    win.restore();
  }

  win.focus();
}



app.on('before-quit', (event) => {
  app.isQuitting = true
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  try{
      // Set app user model id for windows
      electronApp.setAppUserModelId(import.meta.env.VITE_ELECTRON_APP_ID)

      // Default open or close DevTools by F12 in development
      // and ignore CommandOrControl + R in production.
      // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
      app.on('browser-window-created', (_, window) => {
        optimizer.watchWindowShortcuts(window)
      })
      
      // const port = 51295
      const port = await getAvailablePort()

      ipcMain.on('get-port', async (event) => {
        event.returnValue = port;
      });

      ipcMain.on('get-proxy-host', (event) => {
        let host = `http://localhost:${port}`

        if (! is.dev){
          host += `/api`
        }

        event.returnValue = host
      });

      await restoreOrCreateWindow()

      // 设置 IPC 处理程序
      setupIpcHandlers(win, app, conf)

      const server = new Server(port, conf)
      
      // 启动服务器
      server
        .start()
        .then(() => {
          console.log('Server started successfully');
        })
        .catch((err) => {
          log.error('Error starting server:', err);
          console.error('Error starting server:', err);
        });

      app.on('activate', restoreOrCreateWindow)
  }catch(e){
    console.error(e)
    log.error('Error during app initialization:', e);
    app.quit();
  }
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    if (app.isQuitting) {
      app.quit()
    }
  }
})

function versionsPrint() {
  // electron 版本
  console.log('process.versions.electron', process.versions.electron);

  // ABI版本
  console.log('process.versions.modules', process.versions.modules);

  // NODE版本
  console.log('process.versions.node', process.versions.node);

  // V8 引擎版本
  console.log('process.versions.v8', process.versions.v8);

  // chrome版本
  console.log('process.versions.chrome', process.versions.chrome);

  // 架构信息
  console.log('process.env.PROCESSOR_ARCHITECTURE', process.env.PROCESSOR_ARCHITECTURE);

  log.info('process.versions.electron', process.versions.electron);
  log.info('process.versions.modules', process.versions.modules);
  log.info('process.versions.node', process.versions.node);
  log.info('process.versions.v8', process.versions.v8);
  log.info('process.versions.chrome', process.versions.chrome);
  log.info('process.env.PROCESSOR_ARCHITECTURE', process.env.PROCESSOR_ARCHITECTURE);
}

versionsPrint();
